package com.panda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.panda.entity.po.LoginUser;
import com.panda.entity.po.User;
import com.panda.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service("userDetailsServiceImpl")
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;

    @Autowired
    public UserDetailsServiceImpl(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户
        LambdaQueryWrapper<User> wrapper_user = new LambdaQueryWrapper<>();
        wrapper_user.eq(User::getUsername, username);
        User user = userMapper.selectOne(wrapper_user);
        //判断是否存在用户
        if (Objects.isNull(user)) {
            throw new RuntimeException("用户不存在");
        }
        return new LoginUser(user);
    }
}
